import React from "react"
import {message} from "antd";

const token = localStorage.getItem("token");

//检查请求状态
export function checkStatus(response) {
    if (response.status > 200 && response.status < 500) {
        const error = new Error("请求异常" + response.status.toString())
        error.response = response;
        throw error
    }
    const contentType = response.headers.get('Content-Type');
    if (contentType.includes('application/json')) {
        return response.json().then(result => {
            // 1002 表示需要调转页面(如未登录时需要跳转cas认证中心)
            if (result.code === 1002) {
                window.location.href = result.data;
                return;
            }
            if (result.code !== 0) {
                throw Error(result.msg || result.message || '接口错误！');
            }
            return result.data;
        });
    }
    return response;

}

export default function post(url, paramObject) {
    return fetch(url, {
        method: "post",
        headers: {
            "content-type": "application/json",
            "token": token,
        },
        body: JSON.stringify(paramObject),
    }).then(checkStatus).catch((err) => message.error(err.message))
}

export function login(url, data) {
    const parms = "username="+data['username']+"&password="+data['password']+"&client_id=c1&client_secret=secret&grant_type=password"
    return fetch(url, {
        method: "post",
        headers: {
            "content-type": "application/x-www-form-urlencoded",
            "token": token,
            "client": "web"
        },
        body: parms
    }).then((res)=>{
        if (res.status !== 200) {
            const contentType = res.headers.get('Content-Type') || '';
            if (contentType.includes('application/json')) {
                res.json().then(result => {
                    message.error(result.error_description)
                })
            }else{
                message.error("未知错误！")
            }
        } else {
            res.json().then(result => {
                localStorage.setItem("token", result.access_token)
                localStorage.setItem("username", data['username'])
                this.props.history.push("/")
            })
        }
    }).catch((err) => message.error(err.message))
}

/**
 * post下载
 * @param url
 * @param paramObject
 * @returns {Promise<Response | never>}
 */
export const download = (url, paramObject) => {
    return fetch(url, {
        method: "post",
        headers: {
            "content-type": "application/json",
            "token": token,
        },
        body: JSON.stringify(paramObject),
    }).then(checkStatus).then(
        (response) => {
            response.blob().then(blob => {
                const fileName = response.headers.get('content-disposition').split('=')[1];

                const url = window.URL.createObjectURL(blob);   // 获取 blob 本地文件连接 (blob 为纯二进制对象，不能够直接保存到磁盘上)
                const a = document.createElement('a');
                a.href = url;
                a.download = decodeURIComponent(fileName);

                document.body.appendChild(a);
                a.click();
            })
        }
    )
}

export const get = (url, params) => {
    if (params) {
        let paramsArray = [];
        //拼接参数
        Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
        if (url.search(/\?/) === -1) {
            url += '?' + paramsArray.join('&')
        } else {
            url += '&' + paramsArray.join('&')
        }
    }
    //fetch请求
    return fetch(url, {
        method: 'GET',
    }).then(checkStatus).catch((err) => alert(err.message))
}


/**
 * POST请求
 * @param url 路径
 * @param paramObject 参数
 */
export const gatewayPost = (url, paramObject) => post(`/api${url}`, paramObject);


/**
 * 下载请求
 * @param url 路径
 * @param paramObject 参数
 */
export const gatewayDownload = (url, paramObject) => download(`/api${url}`, paramObject);

